import styles from '../styles.less';
import {Dropdown, Pagination, Space, Table, Tag, Popover, App} from 'antd';
import {useCallback, useEffect} from 'react';
import Opera from './Opera';
import {connect, useAccess} from 'umi';
import {DownOutlined, ExclamationCircleFilled} from '@ant-design/icons';

const DataTable = (props) => {

  const access = useAccess();
  const {modal} = App.useApp();
  const {dispatch, dataTable, submitting, loading} = props;
  const {setDataForm, tablePayload, setTablePayload, setTriggerJobForm, setLogTable} = props.data;

  /* 获取列表 */
  const getAllByPage = useCallback((payload) => {
    dispatch({
      type: 'PMonitorXxlJob/getAllByPage',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    getAllByPage(tablePayload);
  }, [getAllByPage, tablePayload]);

  /* 查询日志 */
  function logs(record) {
    setLogTable({
      visible: true,
      title: '查询日志',
      data: record,
    });
  }

  /* 启动 */
  function start(record) {
    if (!submitting) {
      modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定启动任务？',
        okText: "确认",
        cancelText: "取消",
        onOk() {
          dispatch({
            type: 'PMonitorXxlJob/start',
            payload: record.id,
            callback: () => {
              setTablePayload({...tablePayload});
            },
          });
        },
      });
    }
  }

  /* 停止 */
  function stop(record) {
    if (!submitting) {
      modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定停止任务？',
        okText: "确认",
        cancelText: "取消",
        onOk() {
          dispatch({
            type: 'PMonitorXxlJob/stop',
            payload: record.id,
            callback: () => {
              setTablePayload({...tablePayload});
            },
          });
        },
      });
    }
  }

  /* 执行一次 */
  function trigger(record) {
    setTriggerJobForm({
      visible: true,
      title: '执行一次',
      data: record,
    });
  }


  /* 编辑 */
  function edit(e, record) {
    e.preventDefault();
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
    return false;
  }

  /* 删除 */
  function del(e, record) {
    e.preventDefault();
    if (!submitting) {
      modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定删除数据？',
        okText: "确认",
        cancelText: "取消",
        onOk() {
          dispatch({
            type: 'PMonitorXxlJob/del',
            payload: [record.id],
            callback: () => {
              setTablePayload({...tablePayload, page: 1});
            },
          });
        },
      });
    }
    return false;
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.page - 1) * tablePayload.size + index + 1}
        </span>
      ),
    },
    {
      title: '任务描述',
      dataIndex: 'jobDesc',
      ellipsis: true,
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.jobDesc ? record.jobDesc : '-'}</span>
        );
      },
    },
    {
      title: '调度配置',
      dataIndex: 'scheduleConf',
      ellipsis: true,
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.scheduleType + '：' + record.scheduleConf}</span>
        );
      },
    },
    {
      title: '下次执行时间',
      dataIndex: 'nextTriggerTime',
      align: 'center',
      render: (_, record) => {
        return (
          <Popover content={() => {
            let content = [];
            record.nextTriggerTime.forEach(d => {
              content.push(<p key={d}>{d}</p>);
            });
            return (
              <div>{content}</div>
            );
          }} title='下次执行时间' trigger='hover'>
            <span style={{color: '#0958d9'}}>下次执行时间</span>
          </Popover>
        );
      },
    },
    {
      title: '执行方法',
      dataIndex: 'executorHandler',
      ellipsis: true,
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.glueType + '：' + record.executorHandler}</span>
        );
      },
    },
    {
      title: '调度状态',
      dataIndex: 'triggerStatus',
      align: 'center',
      render: (_, record) => {
        return (
          <Tag color={record.triggerStatus === 1 ? 'geekblue' : 'volcano'}>
            {record.triggerStatus === 1 ? '运行' : '停止'}
          </Tag>
        );
      },
    },
    {
      title: '注册节点',
      dataIndex: 'xxlJobGroup',
      align: 'center',
      render: (_, record) => {
        return (
          <Popover content={() => {
            let content = [];
            if (record.xxlJobGroup && record.xxlJobGroup.addressList) {
              record.xxlJobGroup.addressList.split(',').forEach(d => {
                content.push(<p>{d}</p>);
              });
            }
            return (
              <div>{content}</div>
            );
          }} title='注册节点' trigger='hover'>
            <span style={{color: '#0958d9'}}>注册节点</span>
          </Popover>
        );
      },
    },
    {
      title: '负责人',
      dataIndex: 'author',
      ellipsis: true,
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.author ? record.author : '-'}</span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      render: (_, record) => {
        let items = [];
        if (access?.xxlJob_log_list) {
          items = [...items, {key: 'logs', label: '查询日志', onClick: () => logs(record)}];
        }
        if (access?.xxlJob_info_trigger) {
          items = [...items, {key: 'trigger', label: '执行一次', onClick: () => trigger(record)}];
        }
        if (access?.xxlJob_info_start && record.triggerStatus === 0) {
          items = [...items, {key: 'start', label: '启动', onClick: () => start(record)}];
        }
        if (access?.xxlJob_info_stop && record.triggerStatus === 1) {
          items = [...items, {key: 'stop', label: '停止', onClick: () => stop(record)}];
        }
        return (
          <Space size='small'>
            {access?.xxlJob_info_edit && (
              <a onClick={e => edit(e, record)}>编辑</a>
            )}
            {access?.xxlJob_info_del && (
              <a onClick={e => del(e, record)}>删除</a>
            )}
            {(items.length > 0) && (
              <Dropdown arrow menu={{items}}>
                <a onClick={(e) => e.preventDefault()}>
                  更多<DownOutlined/>
                </a>
              </Dropdown>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <div className={styles.myDataTable}>
        <Opera data={{setDataForm}}/>
        <Table
          className={styles.myTable} bordered={false} size={'middle'} columns={columns}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{y: '100%'}} loading={loading}
        />
      </div>
      <Pagination
        pageSize={tablePayload.size} current={tablePayload.page} total={dataTable.total}
        className={styles.myPagination} size={'default'} hideOnSinglePage={false}
        showTotal={(total) => {
          return `共 ${total} 条记录`;
        }}
        pageSizeOptions={[15, 30, 60, 120]}
        showSizeChanger showQuickJumper={true}
        onChange={(page, pageSize) => {
          setTablePayload({...tablePayload, page: page, size: pageSize});
        }}
      />
    </>

  );
};

export default connect(({loading, PMonitorXxlJob}) => {
  return {
    loading: loading.effects['PMonitorXxlJob/getAllByPage'],
    submitting: loading.effects['PMonitorXxlJob/del'] || loading.effects['PMonitorXxlJob/start'] || loading.effects['PMonitorXxlJob/stop'],
    dataTable: PMonitorXxlJob.dataTable,
  };
})(DataTable);
